﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;
    using TVN.ShopMan.Common;

    public partial class AuthForm : Form
    {
        private static readonly ILogger logger = Program.Logger.CreateChildLogger("AuthForm");
        private IRepository<Account> userRepository = null;

        public AuthForm()
        {
            InitializeComponent();

            this.userRepository = Program.Container.Resolve<IRepository<Account>>();
            this.txtUsername.Text = Environment.UserName;
        }

        private void btnLogOn_Click(object sender, EventArgs e)
        {
            this.btnLogOn.Enabled = false;

            if (AppHelper.IsValidLogOn(this.txtUsername.Text, this.txtPassword.Text))
            {
                try
                {
                    IDictionary propertyNameValues = new Dictionary<String, string>();
                    propertyNameValues.Add(Account.Properties.Username, this.txtUsername.Text);
                    propertyNameValues.Add(Account.Properties.Password, this.txtPassword.Text);

                    IList<Account> accounts = this.userRepository.FindBy(propertyNameValues);
                    if ((accounts != null) && (accounts.Count > 0))
                    {
                        Program.SessionData = new SessionInfo
                        {
                            ActiveAccount = accounts[0],
                            LogOnDate = DateTime.Now
                        };

                        // Save current account information for next session
                        if (this.ckbAutoSave.Checked)
                        {
                        }

                        this.DialogResult = DialogResult.OK;
                        logger.InfoFormat("User: {0} has been authenticated", this.txtUsername.Text);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("Error while logging on", ex);
                }
            }

            this.btnLogOn.Enabled = true;
        }
    }
}
